<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible"
    content="IE=edge">
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 后端返回的数据格式     
    const list = [
      { name: '张三', id: 1, pid: '' },
      { name: '张小三', id: 2, pid: 1 },
      { name: '张小四', id: 3, pid: 1 },
      { name: '王三', id: 4, pid: '' },
      { name: '王小三', id: 5, pid: 4 }]
    function transListToTree(id) {
      let tempArr = []
      list.forEach((item) => {
        if (item.pid === id) {
          tempArr.push(item)
          const children = transListToTree(item.id)
          item.children = children
        }

      })
      return tempArr
    }
    console.log(transListToTree(''));
  </script>
</body>

</html>